<template>
    <div class="page-wrap">
		<!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
			<div class="addressIcon"></div>
			<span>当前位置：</span>
			<span style="cursor: pointer" @click="returnImage">指导书管理</span>
			<Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
			<span style="color: #333" v-text="guidbookname">{{guidbookname}}</span>
		</div> -->
    <div class="page-content" :style="{height:contentHei}">
			<div class="img-header">
				<div style="font-weight: 700;font-size: 18px">{{guidbookname}}编辑</div>
			</div>
			<Divider />
      <div class="content-wrap">
    <mavon-editor ref="md" @imgAdd="$imgAdds" @imgDel="$imgDels"
                            v-model="currentGuideContent"
                            :ishljs="true"
                            :code_style="code_style"
                            :externalLink="externalLink"
														:toolbars="toolbars"
                            :toolbarsFlag="true">
						<template slot="left-toolbar-after">
							<div :class="{'selected': s_img_dropdown_open}" type="button"  @mouseleave="$mouseleave_img_dropdown" @mouseenter="$mouseenter_img_dropdown"
                class="op-icon fa fa-mavon-picture-o dropdown dropdown-wrapper"
                aria-hidden="true">
            		<transition name="fade">
                <div  class="op-image popup-dropdown" :class="{'transition': true}" v-show="s_img_dropdown_open" @mouseleave="$mouseleave_img_dropdown" @mouseenter="$mouseenter_img_dropdown">
                    <div  class="dropdown-item" @click.stop="$toggle_imgLinkAdd('imagelink')"><span>从系统中添加图片</span></div>
                    <div class="dropdown-item" style="overflow: hidden">
                        <input type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" @change="$imgAdd($event)" multiple="multiple"/>上传图片
                    </div>
                </div>
            </transition>
        	</div>
  			</template>
			</mavon-editor>
      </div>
      <div style="margin-top: 15px;display: flex;justify-content: end;align-items: center">
					<div>
							<Button type="primary" size="large" @click="saveBtn()">保存</Button>
              <Button size="large" @click="cancle()">取消</Button>
					</div>
				</div>
    </div>
		 <!--图片列表-->
       <DrawerPage
            v-model="imgModal"
            select
            title="封面图片"
            :columns="videoCol" 
            :data="videoList" 
            :loading="fileListLoading"
            :total='videoTotal' 
            :size.sync="videoPageSize" 
            :page.sync="videoPage"
            @queryFun="getVideoList"
        >
            <ResourseUsageIllustrate type="课程" slot="rule"></ResourseUsageIllustrate>
            <template slot="search">
                <i-select clearable v-model="searchFilePublic" placeholder="可见范围" style="width: 150px;margin-left: 15px" @on-change="searchFile">
                    <i-option value="range">平台</i-option>
                    <i-option value="system">系统</i-option>
                    <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
                </i-select>
                <Input v-model.trim="searchFileName" placeholder="图片名称" style="width: 180px;" clearable @on-change="searchFile"/>
                <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshImg()"><i class="el-icon-refresh-right" /></Button>
            </template>
        </DrawerPage>
  </div>
</template>
<script>
import fileEditor from '@/mixin/fileEditor'
import $ from 'jquery'
import encryption from '@/libs/encryption.js'
 import { debounce } from '@/libs/utils'
 import defaultImg from '@/assets/globalIcon/course.jpg'
import {getFilesData} from '@/api/uploadFile.js'
import ResourseUsageIllustrate from '@/components/resourse-usage-illustrate'
import {
	sectionList,
    modifySection,
    donwLoadMdFile,
	} from '@/api/guide.js'
export default {
  mixins:[fileEditor],
	components:{ResourseUsageIllustrate},
  data(){
    let September = sessionStorage.getItem('November')
			September = JSON.parse(encryption.SelfUseDecrypt(September));
    return{
      USER_ID: September.userId,
				fullHeight: document.documentElement.clientHeight,
				fullWidth: document.documentElement.clientWidth,
				contentHei: 'auto',
      guideID:'',
      guidbookname:'',
      currentGuideContent:'',
      currentGuide:{},
      code_style: 'solarized-dark',
			img_file:[],
			toolbars: {
					bold: true, // 粗体
					italic: true, // 斜体
					header: true, // 标题
					underline: true, // 下划线
					strikethrough: true, // 中划线
					mark: true, // 标记
					superscript: true, // 上角标
					subscript: true, // 下角标
					quote: true, // 引用
					ol: true, // 有序列表
					ul: true, // 无序列表
					link: true, // 链接
					imagelink: false, // 图片链接
					code: true, // code
					table: true, // 表格
					//fullscreen: true, // 全屏编辑
					readmodel: true, // 沉浸式阅读
					htmlcode: true, // 展示html源码
					help: true, // 帮助
					/* 1.3.5 */
					undo: true, // 上一步
					redo: true, // 下一步
					trash: true, // 清空
					// save: false, // 保存（触发events中的save事件）
					/* 1.4.2 */
					navigation: true, // 导航目录
					/* 2.1.8 */
					alignleft: true, // 左对齐
					aligncenter: true, // 居中
					alignright: true, // 右对齐
					/* 2.2.1 */
					subfield: true, // 单双栏模式
					preview: true, // 预览
			},
      externalLink: {
           markdown_css: function () {
                        // 这是你的markdown css文件路径
                        return `/bdesigner/markdown/github-markdown.min.css`;
                    },
                    hljs_js: function () {
                        // 这是你的hljs文件路径
                        return `/bdesigner/highlightjs/highlight.min.js`;
                    },
                    hljs_css: function (css) {
                        // 这是你的代码高亮配色文件路径
                        return `/bdesigner/highlightjs/styles/${css}.min.css`;
                    },
                    hljs_lang: function (lang) {
                        // 这是你的代码高亮语言解析路径
                        return `/bdesigner/highlightjs/languages/${lang}.min.js`;
                    },
                    katex_css: function () {
                        // 这是你的katex配色方案路径路径
                        return `/bdesigner/katex/katex.min.css`;
                    },
                    katex_js: function () {
                        // 这是你的katex.js路径
                        return `/bdesigner/katex/katex.min.js`;
                    },
        },
				//markdown编辑器增加系统文件上传
				imgModal:false,
				videoPage:1,
				videoPageSize:10,
				searchFileName:'',
				searchFilePublic:'',
				fileListLoading:false,
                imgFromSystem:false,
                useImagePath:'',
				videoList:[],
				videoTotal:0,
				setUserTableHei:'700',
				videoCol:[
                    {
                        title:'名称',
                        key:'originName',
                        align:'center',
                        // render:(h,params)=>{
                        //     let fileName = params.row.fileName
                        //     fileName = fileName.split('.')[0]
                        //     return h('div',fileName)
                        // }
                    },
                    {
                    	title:'缩略图',
                    	key:'path',
                    	align:'center',
                    	render:(h,params) => {
                    		return h('img',{
                    			attrs:{
                    				src:this.handleImage(params.row.path)
                    			},
                    			style:{
                    				display:'inline-block',
                    				maxHeight:'40px',
                    				width:'auto',
                    				verticalAlign:'middle'
                    			}
                    		})
                    	}
                    },
                    {
                        title:'ID',
                        key:'id',
                        align:'center',
                    },
//                  {
//                      title:'类型',
//                      key:'bucket',
//                      align:'center',
//                      width:80,
//                  },
					{
						title: '可见范围',
						key: 'visibility',
						width: 100,
						align: 'center',
						render: (h, params) => {
							return h('div', {
								style: {
									color: this.handlePublic(params.row.visibility).color
								}
							}, this.handlePublic(params.row.visibility).text)
						}
					},
                    {
                        title:'内容',
                        key:'check',
                        align:'center',
                        width:100,
                        render: (h, params) => {
                            return h('div', [
                                h('a', {
                                    on:{
                                        click:()=>{
                                            this.checkInfo(params);
                                        }
                                    }
                                }, '查看')
                            ]);
                        }
                    },
                    {
                        title:'创建者',
                        key:'creatorName',
                        align:'center',
                    },
                    {
                        title:'创建时间',
                        key:'created',
                        align:'center',
                    },
                    {
                        title:'操作',
                        key:'action',
                        width:100,
                        align:'center',
                        render:(h,params)=>{
                            let text = ''
                            if(params.row.imgUseFlag){
                                text = '已用'
                            }else {
                                text = '使用'
                            }
                            let status = this.getResourceDisStatus(params.row.visibility === 'private',params.row.creator);
                            return h('a',{
                                style: {
//                                  'display': 'flex',
//                                  'justify-content': 'flex-start',
//                                  'align-items': 'center',
                                    color:params.row.imgUseFlag?'#2f70ff':'grey',
                                    cursor:status ? 'not-allowed' : 'pointer'
                                },
                            },[
                                h('div', {
                                    on: {
                                        'click': ()=>{
                                        	if(status){
                                                //单位的指导书不能选个人资源
	                                        	return; 
										 }
                                            this.chooseImg(params)
                                        },
                                    },
                                    style:{
//                                      'margin-left':'15px',
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: params.row.imgUseFlag?require('../../assets/globalIcon/choosed.png'):require('../../assets/globalIcon/add.png'),
                                        },
                                        style: {
                                            'margin-right':'5px',
                                            'vertical-align': 'middle',
                                            width:'16px',
                                            height:'16px',
                                            display:'inline-block',
                                        },
                                    }),
                                    h('span',{},text)
                                ])
                            ])
                        }
                    },
                ],
    }
  },
  mounted(){
    this.setStyle()
    	window.onresize = () => {
				this.setStyle()
			}
		this.img_file = this.$refs.md.$refs.toolbar_left.img_file;
    this.guideID = this.$route.query.guidbookid
		this.guidbookname = this.$route.query.guidbookname
        this.addBreadItem({ name: this.guidbookname });
    //根据id获取指导书详情
    this.getGuideDetail()
  },
  methods:{
    	// 设置高度
			setStyle() {
				window.fullHeight = document.documentElement.clientHeight;
				window.fullWidth = document.documentElement.clientWidth;
				this.fullHeight = window.fullHeight;
				this.fullWidth = window.fullWidth;
				this.contentHei = this.fullHeight - 60 - 21 + 'px' // 80是头部高度  60是上下padding
				let hei = this.fullHeight - 60 - 21 - 96 - 114 - 74 + 'px'
				 this.setUserTableHei = this.fullHeight - 212;
				 this.videoPageSize = Math.floor(this.setUserTableHei/50) - 1
				$('.content-wrap .ql-container').css('height', hei)
			},
    // 返回指导书管理
			returnImage() {
				this.$router.push({
					name: 'guide',
					query: {
						page: this.$route.query.page,
					}
				})
			},
    getGuideDetail(){
      sectionList(this.guideID).then(data => {
					if(data.code == 1) {
            if(data.attribute.datalist&&data.attribute.datalist.length){
              this.currentGuideContent = data.attribute.datalist[0].sectiontext;
              this.currentGuide = data.attribute.datalist[0]
            }
					} else {
						this.currentGuideContent = '';
            this.currentGuide = {}
						this.$Message.error(data.message);
					}
				}).catch(error => {
					console.log(error);
				})
    },
		 saveBtn: debounce(function() {
                this.saveBtnD()
            },500),
    saveBtnD(){
      let params = {...this.currentGuide};
      params.sectiontext = this.currentGuideContent;
      if(!params.sectiontext){
        this.$Message.info('指导书内容不能为空');
        return;
      }
      modifySection(params,params.sectionid).then(res=>{
        if(res.code == 1) {
						this.$Message.success({
							content: '修改成功！',
							duration: 3,
									});
					this.getGuideDetail();
      }else{
        this.$Message.error({
          content:res.message,
          duration: 3,
        })
      }
    })
  },
  cancle(){
    this.getGuideDetail();
  },
	//添加系统文件功能
	$toggle_imgLinkAdd() {
        this.videoPage = 1
        this.searchFileName = ''
        this.searchFilePublic = ''
     this.getVideoList();
    },
	 // 选择图片
            getVideoList(){
                this.imgModal = true
                let params = {
                    pageIndex:this.videoPage,
                    pageSize:this.videoPageSize
                }
                let data = {
                	bucket:'images',
                }
                if($.trim(this.searchFileName) != ''){
                    data.originName = $.trim(this.searchFileName)
                }
                if($.trim(this.searchFilePublic) != ''){
                	data.visibility = $.trim(this.searchFilePublic)
                }
                this.fileListLoading = true
                getFilesData(params,data)
                    .then((res)=>{
                        if(res.data.code == 1){
                            let attribute = res.data.data;
                            let items = attribute.list;
                            this.videoTotal = attribute.total;
                            for(let i=0;i<items.length;i++){
                                items[i].imgUseFlag = false
                                if(items[i].path === this.useImagePath){
                                    items[i].imgUseFlag = true
                                }
                            }
                            this.videoList = items;
                        }
                        this.fileListLoading = false
                    })
                    .catch((err)=>{
                        this.fileListLoading = false
                    })
            },
            videoOnChange(val){
                this.videoPage = val;
                this.getVideoList();
            },
            searchFile(val){
                this.videoPage = 1
                this.getVideoList();
            },
            refreshImg(){
                this.videoPage = 1
                this.searchFileName = ''
                this.searchFilePublic = ''
                this.getVideoList()
            },
            closeImgModalBtn(){
                this.imgModal = false
            },
            checkInfo(params){
                let path = params.row.path;
                window.openTrain(`/api/minio/filePreview?path=${path}`);
            },
            chooseImg(params){
                if(params.row.imgUseFlag){
                    this.$Message.info({
                        content:'已使用该图片！',
                        duration:3,
                    })
                }else {
                    let _index = params.row._index
                    for(let i=0;i<this.videoList.length;i++){
                        this.videoList[i].imgUseFlag = false
                    }
                    this.$set(this.videoList[_index],'imgUseFlag',true)
                    // this.formValidate.topology = params.row.originName
                    this.useImagePath =  params.row.path
                    //存储图片可见范围
					this.useImageVisibility = params.row.visibility
                    this.imgFromSystem = true;
                    donwLoadMdFile({path:this.useImagePath}).then(res => {
                        if(res.code&&res.code==500){
                            console.log('文件加载失败');
                            return;
                        }else{
                            let file = res;
                            let tempfile = null;     //新建一个变量
                            tempfile = new File([file], `${params.row.originName}`, {
                                type: "image/",  //传参
                                lastModified: Date.now(),
                            });
                            console.log(tempfile); //这样就得到了一个file文件
                            this.$refs.md.$refs.toolbar_left.$imgFileAdd(tempfile)
                        }
                        });
                }
            },
            // 清空选择的图片
            clearImg(){
                this.formValidate.topology = ''
                this.useImagePath =  ''
            },
            handleImage(logo){
                let src = ''
                if(logo){
                    if(logo.indexOf('Learn') > -1){
                        src = logo
                    }else {
                        src = `/Learn/${logo}`
                    }
                }else {
                    src = this.defaultImg
                }
                return src
            },
						 handlePublic(val){
                let obj = {
                    text:'',
                    color:'#8d95a6'
                }
                switch (val){
                    case 'person':
                    case 0:
                    case '0':
                        return obj = {
                            text:'个人',
                            color:'rgb(255, 165, 0)',
                        }
                        break;
                    case 'company':
                    case 1:
                    case '1':
                        return obj = {
                            text:'单位',
                            color:'rgb(50, 205, 50)',
                        }
                        break;
                    case 'system':
                    case 2:
                    case '2':
                        return obj = {
                            text:'系统',
                            color:'rgb(65, 105, 225)',
                        }
                        break;
                  case 'range':
                  case 3:
                  case '3':
                    return obj = {
                      text:'平台',
                      color:'#ff61f4',
                    }
                    break;
                }
            },
			getResourceDisStatus(isPrivate,creator){
                let isNotOwn = this.USER_ID !== creator; 
				let isNotCommonCreator = this.$route.query.creator !== creator;
                let isPublic = this.$route.query.ispublic==1;
               return (isPublic || (isNotOwn && isNotCommonCreator)) && isPrivate
			},
    }
  }
</script>
<style lang="stylus" scoped>
    .op-icon.dropdown-wrapper.dropdown
        position relative
        &[type=button]
            -webkit-appearance unset
        .popup-dropdown
            position absolute
            display block
            background #fff
            top 32px
            left -45px
            min-width 130px
            z-index 1600
            border 1px solid #ebeef5
            border-radius 4px
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)
            .dropdown-item:first-child
                border-top-left-radius 3px
                border-top-right-radius 3px
            .dropdown-item:last-child
                border-bottom-left-radius 3px
                border-bottom-right-radius 3px
            &.op-header
                left -30px
                min-width 90px
            &.fade-enter-active, &.fade-leave-active
                opacity 1
            &.fade-enter, &.fade-leave-active
                opacity 0
            &.transition
              &, .dropdown-item
                transition all 0.2s linear 0s
        .dropdown-item
            height 40px
            line-height @height
            font-size 14px
            color #606266
            position relative
            &:hover
                color #303133
                background-color #e9e9eb
            input
                position absolute
                font-size 100px
                right 0
                top 0
                opacity 0
                cursor pointer
        .dropdown-images
            box-sizing border-box
            button
                position absolute
                top -1px
                right 5px
                font-size: 14px
                &:hover
                    color #F56C6C
                    background-color: transparent
            span
                display inline-block
                width 80px
                white-space nowrap
                overflow hidden
                text-overflow ellipsis
            &:hover
                .image-show
                    display block !important
            .image-show
                display none
                position absolute
                left -128px
                top 0
                width 120px
                height 90px
                object-fit contain
                border 1px solid #F2F6FC
                &.transition
                    transition all 0.2s linear 0s
            &.transition
                transition all 0.2s linear 0s
.add-image-link-wrapper
    position fixed
    left 0
    right 0
    top 0
    bottom 0
    background rgba(0, 0, 0, 0.7)
    z-index 1600
    transition all 0.1s linear 0s
    &.fade-enter-active, &.fade-leave-active
        opacity 1
    &.fade-enter, &.fade-leave-active
        opacity 0
    .add-image-link
        position fixed
        box-sizing border-box
        text-align center
        width 24%
        left 38%
        @media only screen and (max-width 1500px)
            width 34%
            left 33%
        @media only screen and (max-width 1000px)
            width 50%
            left 25%
        @media only screen and (max-width 600px)
            width 80%
            left 10%
        height auto
        padding 40px
        top 25%
        transition all 0.1s linear 0s
        z-index 3
        background #fff
        border-radius 2px

        i
            font-size 24px
            position absolute
            right 8px
            top 6px
            color rgba(0, 0, 0, 0.7)
            cursor pointer
        .title
            font-size 20px
            margin-bottom 30px
            margin-top 10px
            font-weight 500 !important
        .input-wrapper
            margin-top 10px
            width 80%
            border  1px solid #eeece8
            text-align left
            margin-left 10%
            height 35px
            input
                height 32px
                line-height 32px
                font-size 15px
                width 90%
                margin-left 8px
                border none
                outline none
        .op-btn
            width 100px
            height 35px
            display inline-block
            margin-top 30px
            cursor pointer
            text-align center
            line-height @height
            opacity 0.9
            border-radius 2px
            letter-spacing 1px
            font-size 15px
        .op-btn.sure
            background #2185d0
            color #fff
            margin-left 5%
            &:hover
                opacity 1
        .op-btn.cancel
            border 1px solid #bcbcbc
            color #bcbcbc
            &:hover
                color #000

</style>
<style scoped>
.markdownDraw>>>.ivu-drawer-body{
	overflow: inherit;
}
	
	.page-content {
		background-color: #fff;
		border-radius: 10px;
	}
	
	.img-header {
		display: flex;
		justify-content: space-between;
		padding: 20px 20px 0 20px;
	}
	
	.addressIcon {
		display: inline-block;
		height: 14px;
		width: 12px;
		background: url("../../assets/globalIcon/addressIcon.png") no-repeat center;
		background-size: 100% 100%;
		margin-bottom: -1px;
	}
	
	.content-wrap {
		overflow-x: hidden;
		overflow-y: auto;
		padding: 0 20px 20px 20px;
		height: calc(100% - 160px);
	}
	
	.left-hei {
		overflow-x: hidden;
		overflow-y: auto;
		/*padding-right: 8px;*/
		max-height: calc(100% - 66px);
		/*padding-top: 17px;*/
	}
	
	.title-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px 0;
	}
	
	.titleActive {
		border: 1px solid #1563C2 ;
	}
	
	.title-name {
		display: flex;
		justify-content: flex-start;
		align-items: center;
	}
	
	.page-wrap /deep/.editor .ql-container.ql-snow {
		overflow: hidden auto;
	}
	
	.page-wrap /deep/.editor .ql-editor {
		overflow: auto;
	}
	.page-wrap /deep/ .v-note-wrapper .v-note-op{
		position: sticky;
    top: 0;
	}
	.page-wrap /deep/ .v-note-wrapper{
		z-index:1000;
	}
</style>